package 树;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xebrb2/
 */
public class 二叉树的后序遍历 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private List<Integer> list = new ArrayList<>();

    //递归
    public List<Integer> postorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();

        postorderTraversal(root.left);
        postorderTraversal(root.right);
        list.add(root.val);
        return list;
    }

    //非递归
    /*前序遍历 根 左 右  后序遍历 左 右 根
      将前序遍历的顺序改为根 右 左，在将结果倒叙就是后序遍历的结果
    */

    public List<Integer> postorderTraversalNR(TreeNode root) {
        if(root == null) return new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);

            if(node.left!=null){
                stack.push(node.left);
            }

            if(node.right!=null){
                stack.push(node.right);
            }
        }
        Collections.reverse(list);
        return list;
    }
}
